const fs = require('fs');
const path = require('path');
module.exports = class extends think.Controller {
	async __before() {

	}

	async indexAction() {
		console.log(this.post())
		console.log(this.get())

	}

	async weixinAction() {

		let auth = await this.session("auth");
		let user = await this.session("user") || {};
		if(auth && user.status == 1) {
			let action = this.get("action");
			let wxid = await this.session("wxid");
			let config = JSON.parse(fs.readFileSync(think.resource + "/assets/plugins/ueditor/node/config.json", 'utf8'));
			switch(action) {
				case 'config':
					return this.body = config;
					break;
				case 'uploadimage':
					if(think.isEmpty(wxid)) {
						return this.json({
							state: 'FAIL',
							url: ''
						});
					}

					let file = this.file("Filedata");
					console.log(file);

					let pics = await this.uploadImage(file, "weixin");
					if(think.isEmpty(pics)) {
						return this.json({
							state: '上传失败'

						});

					}
					let api = await this.wechatApi(wxid);
					let res = await api.uploadMaterial(path.join(think.ROOT_PATH, 'www', pics[0].url), 'image');
					console.log(res)
					if(res.url) {
						return this.json({
							state: 'SUCCESS',
							url: res.url,
							title: pics[0].filename,
							original: pics[0].filename,
							type: pics[0].type,
							size: pics[0].size
						});
					} else {
						return this.json({
							state: 'FAIL',
							url: '',
							title: pics[0].filename,
							original: pics[0].filename,
							type: pics[0].type,
							size: pics[0].size
						});
					}

					break;
			}

		} else {
			return this.json({
				state: '权限不足',
				url: '',
				title: '',
				original: '',
				type: '',
				size: 0
			});
		}

	}
	
	
	async storeAction() {

		let auth = await this.session("auth");
		let user = await this.session("user") || {};
		if(auth && user.status == 1) {
			let action = this.get("action");
			
			let config = JSON.parse(fs.readFileSync(think.resource + "/assets/plugins/ueditor/node/config.json", 'utf8'));
			switch(action) {
				case 'config':
					return this.body = config;
					break;
				case 'uploadimage':
					

					let file = this.file("Filedata");
					console.log(file);

					let pics = await this.uploadImage(file, "store");
					if(think.isEmpty(pics)) {
						return this.json({
							state: '上传失败'

						});

					}
					
					
					
						return this.json({
							state: 'SUCCESS',
							url: pics[0].url,
							title: pics[0].filename,
							original: pics[0].filename,
							type: pics[0].type,
							size: pics[0].size
						});
					

					break;
			}

		} else {
			return this.json({
				state: '权限不足',
				url: '',
				title: '',
				original: '',
				type: '',
				size: 0
			});
		}

	}
};